package com.sijia.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.sijia.reggie.comment.BaseContext;
import com.sijia.reggie.comment.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器
 * @author 杨思佳
 * @version 1.0
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    /**
     * 拦截客户端的请求，对其进行校验与放行
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("本次请求：{}", requestURI);
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/upload",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //对请求进行校验
        boolean b = checkUrl(urls, requestURI);
        //若符合放行要求，直接放行
        if (b) {
            log.info("本次请求：{},符合放行要求，直接放行", requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        //若不符合放行要求但用户已登录，直接放行(后台系统)
        if (request.getSession().getAttribute("employee") != null){
            Long currentId = (Long)request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(currentId);
            log.info("用户id:{}已登录，直接放行", request.getSession().getAttribute("employee"));
            filterChain.doFilter(request, response);
            return;
        }
        //若不符合放行要求但用户已登录，直接放行(移动端用户系统)
        if (request.getSession().getAttribute("user") != null){
            Long currentId = (Long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(currentId);
            log.info("用户id:{}已登录，直接放行", request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }
        log.info("用户未登录");
        //不符合放行要求且用户未登录，，由前端进行登录页面的跳转
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 检查路径是否匹配
     *
     * @param req
     * @param urls
     * @return
     */
    public boolean checkUrl(String[] urls, String req) {
        for (String url : urls) {
            boolean res = PATH_MATCHER.match(url, req);
            if (res) {
                return true;
            }
        }
        return false;
    }
}
